import express, { Request, Response } from 'express';
import cors from 'cors';
import dotenv from 'dotenv';
import authRoutes from './routes/auth.routes';
import nginxRoutes from './routes/nginx.routes';
import sslRoutes from './routes/ssl.routes';
import logRoutes from './routes/log.routes';
import path from 'path';
import { ConfigModel } from './models/Config';
import { NginxUtil } from './utils/nginx.util';
import { existsSync } from 'fs';

// 加载环境变量
dotenv.config();

const app = express();
const port = process.env.PORT || 3000;



// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));

// 中间件
app.use(cors());
app.use(express.json());

// API 路由
app.use('/api/auth', authRoutes);
app.use('/api/nginx', nginxRoutes);
app.use('/api/ssl', sslRoutes);
app.use('/api/logs', logRoutes);

// 所有其他请求返回 index.html
app.get('*', (req: Request, res: Response) => {
  const indexPath = path.join(__dirname, 'public', 'index.html');
  if (existsSync(indexPath)) {
    res.sendFile(indexPath);
  } else {
    res.status(404).json({ message: '404 Not Found' });
  }
});

// 错误处理中间件
app.use((err: Error, req: Request, res: Response, _: any) => {
  console.error(err.stack);
  res.status(500).json({ message: '服务器内部错误' });
});

// 加载 Nginx 配置
async function loadNginxConfig() {
  const config = await ConfigModel.getSystemConfig();
  if (config) {
    if (config.nginxExec) {
      process.env.NGINX_EXEC = config.nginxExec;
    }
    if (config.nginxCwd) {
      process.env.NGINX_CWD = config.nginxCwd;
    }
    if (config.nginxConfDir) {
      process.env.NGINX_CONF_DIR = config.nginxConfDir;
    }
    NginxUtil.updateEnv();
  }
}

// 初始化数据库和启动服务器
async function startServer() {
  try {
    await loadNginxConfig();

    app.listen(port, () => {
      console.log(`服务器运行在 http://localhost:${port}`);
    });
  } catch (error) {
    console.error('启动服务器失败:', error);
    process.exit(1);
  }
}

startServer(); 